<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

//权限验证
if( Role::init() == false ){
	exit('没有权限');
}

require $_SERVER['DOCUMENT_ROOT'].'/../_interface/upload.php';

$db = new DB('news');

$title_id = isset($_POST['title_id']) ? h($_POST['title_id']) : '';
$category_id = isset($_POST['parent_id']) ? intval($_POST['parent_id']) : '';
$title = isset($_POST['title']) ? h($_POST['title']) : '';
$seo_keyword = isset($_POST['seo_keyword']) ? str_replace('，', ',', h($_POST['seo_keyword'])) : '';
$seo_description = isset($_POST['seo_description']) ? h($_POST['seo_description']) : '';
$content = isset($_POST['content']) ? preg_replace('/\n/', '', preg_replace('/\r/', '', $_POST['content'])) : '';
$periods = isset($_POST['periods']) ? intval($_POST['periods']) : 0;
$time = (isset($_POST['time'])&&$_POST['time']!='') ? strtotime(h($_POST['time'])) : 0;
$start_time = (isset($_POST['start_time'])&&$_POST['start_time']!='') ? strtotime(h($_POST['start_time'])) : 0;
$end_time = (isset($_POST['end_time'])&&$_POST['end_time']!='') ? strtotime(h($_POST['end_time'])) : 0;
$jb_name = isset($_POST['jb_name']) ? h($_POST['jb_name']) : '';
$mrt_name = isset($_POST['mrt_name']) ? h($_POST['mrt_name']) : '';
$intro = isset($_POST['intro']) ? h($_POST['intro']) : '';
$tags = isset($_POST['tags']) ? h($_POST['tags']) : '';
$url = isset($_POST['url']) ? h($_POST['url']) : '';
$views = (isset($_POST['views']) && $_POST['views']!='') ? intval($_POST['views']) : rand(100,200);
$orders = isset($_POST['orders']) ? intval($_POST['orders']) : 0;
$is_reserved = (isset($_POST['is_reserved']) && intval($_POST['is_reserved'])==2) ? 2 : 1;
$from_to = isset($_POST['from_to']) ? h($_POST['from_to']) : '';
$index_top = (isset($_POST['index_top']) && intval($_POST['index_top'])==2) ? 2 : 1;
$is_publish = (isset($_POST['is_publish']) && intval($_POST['is_publish'])==1) ? 1 : 2;
$publish_time = (isset($_POST['publish_time'])&&$_POST['publish_time']!='') ? strtotime(h($_POST['publish_time'])) : 0;
$old_history_id = isset($_POST['old_history_id']) ? intval($_POST['old_history_id']) : 0;
$edit_uid = Sessions::get('uid');
$updated = time();
$ip = IP::get();

//检验必要参数
if($category_id<0 || $title_id=='' || $title=='' || $old_history_id<1 || $seo_keyword=='' || $seo_description=='' || $from_to==''){
	echo '<script>alert("参数有误！");window.history.go(-1);</script>';
	exit;
}
if($content=='' && $url==''){
	echo '<script>alert("参数有误！");window.history.go(-1);</script>';
	exit;
}
if(strlen($url) > 2)
{
	if(strlen($url) < 7 || strlen($url) > 256 || substr($url, 0, 4) != 'http'){
		echo '<script>alert("外部链接地址必须以http开头且字符长度不能小于7或大于256！");window.history.go(-1);</script>';
		exit;
	}
}

//检查定时发布时间
if($is_publish==1 && $publish_time<=time()){
	echo '<script>alert("定时发布时间必须大于当前时间！");window.history.go(-1);</script>';
	exit;
}

$sql = 'select * from news where title_id="'.$title_id.'" and is_del=1 limit 1';
$rs = $db->query($sql)->getOne();

//嘉宾对话、名人榜、拍卖、最新活动、图片轮播、版主名人堂
if( in_array($category_id, array(34,36,39,40,41,46)) ){
	if( strlen($url) < 2 && $category_id != 46 ){
		echo '<script>alert("参数有误！");window.history.go(-1);</script>';
		exit;
	}
	if( $category_id == 34 ){//拍卖
		if( $start_time  <= 0 || $end_time <= 0 ){
			echo '<script>alert("参数有误！");window.history.go(-1);</script>';
			exit;
		}
		$name = '';
	}elseif( $category_id == 36 ){//嘉宾
		if( $jb_name == '' || $time <= 0 ){
			echo '<script>alert("参数有误！");window.history.go(-1);</script>';
			exit;
		}
		$name = $jb_name;
	}elseif( $category_id == 39 ){//名人
		if( $intro == '' ){
			echo '<script>alert("参数有误！");window.history.go(-1);</script>';
			exit;
		}
		$name = '';
	}elseif( $category_id == 40 ){//最新活动
		if( $content == '' || $intro == '' || $start_time  <= 0 || $end_time <= 0 ){
			echo '<script>alert("参数有误！");window.history.go(-1);</script>';
			exit;
		}
		$name = '';
	}elseif( $category_id == 46 ){//版主名人堂
		if( $mrt_name == '' || $intro == '' ){
			echo '<script>alert("参数有误！");window.history.go(-1);</script>';
			exit;
		}
		$name = $mrt_name;
	}else{
		$name = '';
	}
	if( in_array($category_id, array(36,39,40,41,46)) ){
		if( $_FILES['attach']['size']['images'] > 0 ){
			//上传图片
			$up = new Upload($_FILES);     //创建
			$fs = $up->execute();    //开始执行，并返回数据
			if($fs['images']['flag'] == -2){
				echo '<script>alert("上传图片大于1M！");window.history.go(-1);</script>';
				exit;
			}elseif($fs['images']['flag'] == 1){//上传成功
				$images = $fs['images']['handle_dir'].$fs['images']['name'];
			}else{
				echo '<script>alert("图片上传出错，请重新上传！");window.history.go(-1);</script>';
				exit;
			}
		}else{
			$images = $rs['images'];
		}
	}else{
		$images = '';
	}
}else{
	$name = '';
	$images = '';
}
//视频区上传图片
if( in_array($category_id, array(31)) ){
	if( $_FILES['attach']['size']['images'] > 0 ){
		//上传图片
		$up = new Upload($_FILES);     //创建
		$fs = $up->execute();    //开始执行，并返回数据
		if($fs['images']['flag'] == -2){
			echo '<script>alert("上传图片大于1M！");window.history.go(-1);</script>';
			exit;
		}elseif($fs['images']['flag'] == 1){//上传成功
			$images = $fs['images']['handle_dir'].$fs['images']['name'];
		}else{
			echo '<script>alert("图片上传出错，请重新上传！");window.history.go(-1);</script>';
			exit;
		}
	}else{
		$images = $rs['images'];
	}
}

//更新版本号
$history_sql = 'select history_id,static_url from news_history where title_id="'.$title_id.'" order by history_id desc limit 1';
$history_rs = $db->query($history_sql)->getOne();
if($old_history_id!=$rs['title_history_id']){
	$old = true;
}else{
	$old = false;
}
$title_history_id=$history_rs['history_id']+1;//生成新版本号

//检验标题是否重复
$news_sql = 'select category_id,is_publish,title_id from news where title="'.$title.'" and is_del=1 and LENGTH(empty_id)<1 limit 1';
$news_rs = $db->query($news_sql)->getOne();
if($news_rs['title_id']==true && $news_rs['title_id']!=$title_id && $url==''){
	echo '<script>alert("修改失败，新闻《'.$title.'》已存在！");window.history.go(-1);</script>';
	exit;
}

//如果取消了定时发布
if($is_publish == 2 && $news_rs['is_publish'] == 1 ){
	$publish_time = time();
}

//新闻的栏目改变了，更新栏目counts字段
if($category_id != $rs['category_id']){
	//旧的-1
	$category_sql = 'select id,counts from categories where id='.$rs['category_id'].' and is_del=1 limit 1';
	$category_rs = $db->query($category_sql)->getOne();
	$update_data = array('counts'=>($category_rs['counts']-1));
	$db->table('categories')->where('id='.$rs['category_id'])->update($update_data)->run();
	
	//新的+1
	$category_sql = 'select id,counts,title from categories where id='.$category_id.' and is_del=1 limit 1';
	$category_rs = $db->query($category_sql)->getOne();
	$update_data = array('counts'=>($category_rs['counts']+1));
	$db->table('categories')->where('id='.$category_id)->update($update_data)->run();
	
	$new_category_id = $category_id;//新栏目id，为记录移动准备
	$new_category_title = $category_rs['title'];//新栏目标题，为记录移动准备
}else{
	$category_id = $rs['category_id'];
}

//组装news的update数组
$news_data=array('category_id'=>$category_id,
			'title'=>$title,
			'seo_keyword'=>$seo_keyword,
			'seo_description'=>$seo_description,
			'content'=>$content,
			'images'=>$images,
			'name'=>$name,
			'time'=>$time,
			'start_time'=>$start_time,
			'end_time'=>$end_time,
			'intro'=>$intro,
			'tags'=>$tags,
			'url'=>$url,
			'views'=>$views,
			'orders'=>$orders,
			'is_reserved'=>$is_reserved,
			'from_to'=>$from_to,
			'is_publish'=>$is_publish,
			'publish_time'=>$publish_time,
			'index_top'=>$index_top,
			'title_history_id'=>$title_history_id,
			'edit_uid'=>$edit_uid,
			'updated'=>$updated,
			);
$db->table('news')->where('title_id="'.$title_id.'"')->update($news_data)->run();//更新

//组装history的insert数组
$history_data=array('history_id'=>$title_history_id,
			'title_id'=>$title_id,
			'category_id'=>$category_id,
			'title'=>$title,
			'seo_keyword'=>$seo_keyword,
			'seo_description'=>$seo_description,
			'content'=>$content,
			'images'=>$images,
			'name'=>$name,
			'time'=>$time,
			'start_time'=>$start_time,
			'end_time'=>$end_time,
			'intro'=>$intro,
			'tags'=>$tags,
			'url'=>$url,
			'static_url'=>$history_rs['static_url'],
			'views'=>$views,
			'is_reserved'=>$is_reserved,
			'from_to'=>$from_to,
			'is_publish'=>$is_publish,
			'publish_time'=>$publish_time,
			'create_uid'=>$edit_uid,
			'created'=>$updated,
			);
$db->table('news_history')->insert($history_data)->run();//插入

$track_sql = 'select track_id from news_track where title_id="'.$title_id.'" order by track_id desc limit 1';
$track_rs = $db->query($track_sql)->getOne();
//组装track的insert数组
if($old===true){//没有切换历史版本
	$track_data=array('track_id'=>($track_rs['track_id']+1),
					'title_history_id'=>$title_history_id,
					'title_id'=>$title_id,
					'create_uid'=>$edit_uid,
					'created'=>$updated,
					'changes'=>$rs['title_history_id'].'-'.$title_history_id,
					);
}else{//切换了历史版本
	$track_data=array('track_id'=>($track_rs['track_id']+1),
				'title_history_id'=>$title_history_id,
				'title_id'=>$title_id,
				'create_uid'=>$edit_uid,
				'created'=>$updated,
				'changes'=>$old_history_id.'-'.$title_history_id,
				);
}
$db->table('news_track')->insert($track_data)->run();//插入

//更新大话连体钞期数
if( $category_id == 45 ){
	$periods_sql = 'select id from news_periods where title_id="'.$title_id.'" limit 1';
	$periods_rs = $db->query($periods_sql)->getOne();
	if( $periods_rs['id'] < 1 ){
		$periods_data = array('title_id'=>$title_id,
								'title'=>$title,
								'periods'=>$periods,
								'static_url'=>$history_rs['static_url'],
								'is_del'=>1,
								'created'=>$updated,
								'updated'=>$updated,);
		$db->table('news_periods')->insert($periods_data)->run();
	}else{
		$periods_data = array('periods'=>$periods,'title'=>$title,'static_url'=>$history_rs['static_url'],'is_del'=>1,'updated'=>$updated);
		$db->table('news_periods')->where('title_id="'.$title_id.'"')->update($periods_data)->run();
	}
}else{
	$periods_data = array('is_del'=>2,'updated'=>$updated);
	$db->table('news_periods')->where('title_id="'.$title_id.'"')->update($periods_data)->run();
}

//版主名人堂入库处理
if( $category_id == 46 ){
	$mrt_id_arr = isset($_POST['mrt_id']) ? $_POST['mrt_id'] : array();
	$mrt_orders_arr = isset($_POST['mrt_orders']) ? $_POST['mrt_orders'] : array();
	$mrt_is_del_arr = isset($_POST['mrt_is_del']) ? $_POST['mrt_is_del'] : array();
	$mrt_question_arr = isset($_POST['mrt_question']) ? $_POST['mrt_question'] : array();
	$mrt_answer_arr = isset($_POST['mrt_answer']) ? $_POST['mrt_answer'] : array();
	$mrt_counts = count($mrt_question_arr);
	for( $i=0; $i<$mrt_counts; $i++ ){
		$mrt_id = isset($mrt_id_arr[$i]) ? intval($mrt_id_arr[$i]) : 0;
		$mrt_orders = isset($mrt_orders_arr[$i]) ? intval($mrt_orders_arr[$i]) : 0;
		$mrt_is_del = isset($mrt_is_del_arr[$i]) ? 2 : 1;
		$mrt_question = isset($mrt_question_arr[$i]) ? h($mrt_question_arr[$i]) : '';
		$mrt_answer = isset($mrt_answer_arr[$i]) ? h($mrt_answer_arr[$i]) : '';
		
		$mrt_data = array('question'=>$mrt_question,
							'answer'=>$mrt_answer,
							'orders'=>$mrt_orders,
							'is_del'=>$mrt_is_del,
							'updated'=>$updated,);
		if( $mrt_question != '' && $mrt_answer != '' ){
			if( $mrt_id > 0 ){
				$db->table('news_mrt_q_a')->where('id='.$mrt_id)->update($mrt_data)->run();
			}else{
				$mrt_data['title_id'] = $title_id;
				$mrt_data['created'] = $updated;
				$db->table('news_mrt_q_a')->insert($mrt_data)->run();
			}
		}
	}
}

//静态目录下生成index.php
/*$static_path = $root.'www'.substr($history_rs['static_url'], 20);
$php_filename = 'index.php';
$news_content_array = explode('_ueditor_page_break_tag_', $content);
$pages = count($news_content_array);
for( $page=0; $page<=$pages; $page++ ){
	if( $page == 0 ){
		$php_path = $static_path.'/';
	}else{
		$php_path = $static_path.'-'.$page.'/';
	}
	$this_page = ($page > 0) ? $page : 1;
	$php_data = '<?php echo file_get_contents("http://news.zgqw.com/article.php?title_id='.$title_id.'&page='.$this_page.'"); ?>';
	Caches::mkdirs( $php_path );
	file_put_contents($php_path.$php_filename, $php_data);
	
	if( file_exists($php_path.'index.html') ){
		@unlink($php_path.'index.html');
	}
}

//静态目录下生成index.html
if( $is_publish==2 ){//没有设定定时发布
	$service_port = 10001;
	$address = 'localhost';

	$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	
	if( $socket !== false ){
		$result = @socket_connect($socket, $address, $service_port);
		if( $result !== false ){
			$socket_data = 'zgqw2013jjflycontentjjfly'.$static_path.'jjfly'.$title_id.'jjfly'.$pages;
			socket_write($socket, $socket_data, strlen($socket_data));
			socket_close($socket);
		}
	}
}*/

//记录动作日志
Log::logs_articles($category_id, 15, $title_id, $title);

$error_title = '编辑成功 - 编辑文章';
$error_content = '编辑成功！';
$error_pre_button = '<a href="/admin/news/news_lists.php?category_id='.$category_id.'" style="margin-right:20px;" id="pre_button">〈〈 返回列表</a>';
$error_next_button = '<a href="/admin/news/news_edit.php?title_id='.$title_id.'">继续编辑 〉〉</a>';
require template('admin/news/news_error');
exit;